package myJs.cps

import cats.effect.SyncIO
import myJs.Implicits._
import myJs.myPkg.reactHookForm.ReactHookForm
import myJs.tool.Tool
import myJs.tool.Tool._

import scala.collection.immutable.SeqMap
import scala.scalajs.js
import japgolly.scalajs.react.vdom.all._
import japgolly.scalajs.react._
import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react.util.EffectCatsEffect._
import myJs.myPkg.Hooks._
import myJs.Utils._

/** Created by yz on 3/11/2020
  */
object SelectCp {

  case class Props(
      value: String = "",
      onChange: String => SyncIO[Unit] = v=>SyncIO{},
      label: String,
      name: String,
      optionMap: SeqMap[String, String],
      questionInfo: String = "",
      show: Boolean = true,
      selfClass: String = "",
      disabled: Boolean = false
  ){
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    useEffect(
      SyncIO{
        Tool.popover
        ()
      },
      List()
    )
    val useForm = ReactHookForm.useFormContext()
    val hasErrorCls = if (useForm.formState.errors.deepDefinedAt(props.name)) "has-error" else ""
    val displayStr = if (props.show) "block" else "none"
    div(
      paddingRight := "0px", paddingLeft := "0px", display := displayStr,
      className := s"form-group col-sm-12 ${hasErrorCls}",
      label(
        className := s"",
        s"${props.label}",
        if (props.questionInfo.nonBlank) {
          span(
            className := "",
            a(
              `type` := "button",
              className := "selfQuestion",
              title := messages("note"),
              dataContainer := "body",
              dataToggle := "popover",
              dataHtml := "true",
              dataPlacement := "left",
              dataContent := props.questionInfo,
              i(className := "fa fa-question-circle-o")
            )
          )
        } else EmptyVdom,
        ":"
      ),
      PureSelectCp.Props(
        name = props.name,
        value = props.value,
        onChange = props.onChange,
        selfClass = props.selfClass,
        optionMap = props.optionMap,
        disabled = props.disabled
      ).render
    )

  }
}
